import requests
import json
import time
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font
from random import choice
import tkinter as tk
from tkinter import messagebox, simpledialog, ttk
from tkinter import filedialog


class DailyPlanner:
    def __init__(self, excel_path):
        self.excel_path = excel_path
        self.weather_api = 'http://www.weather.com.cn/weather/'
        self.city = '101010100'
        self.weather_data = {}
        self.default_time_slots = [
            '9:00-10:00', '10:00-12:00', '13:30-15:00',
            '15:00-17:00', '17:00-18:00', '19:30-20:30', '20:30-22:00'
        ]

        # 初始化样式
        self.init_styles()

    def init_styles(self):
        # 定义常用样式
        self.styles = {
            'title': PatternFill("solid", fgColor='CDC9C9'),
            'date': PatternFill("solid", fgColor='FFF68F'),
            'weather': PatternFill("solid", fgColor='E066FF'),
            'temp_high': PatternFill("solid", fgColor='EE5C42'),
            'temp_low': PatternFill("solid", fgColor='87CEFF'),
            'time': PatternFill("solid", fgColor='EEA9B8'),
            'plan': PatternFill("solid", fgColor='B0E2FF'),
            'completed': PatternFill("solid", fgColor='90EE90'),
            'not_completed': PatternFill("solid", fgColor='EE5C42'),
            'partial': PatternFill("solid", fgColor='9F79EE'),
            'judge': PatternFill("solid", fgColor='D1EEEE'),
            'review': [
                PatternFill("solid", fgColor='FF6EB4'),
                PatternFill("solid", fgColor='FFD700'),
                PatternFill("solid", fgColor='B0E2FF'),
                PatternFill("solid", fgColor='C1FFC1'),
                PatternFill("solid", fgColor='BCD2EE'),
                PatternFill("solid", fgColor='B03060'),
                PatternFill("solid", fgColor='9F79EE'),
                PatternFill("solid", fgColor='48D1CC'),
                PatternFill("solid", fgColor='EEEE00'),
                PatternFill("solid", fgColor='8B5F65')
            ]
        }

        # 定义字体
        self.fonts = {
            'header': Font(name=u'宋体', size=13, color='FF000000'),
            'date': Font(name=u'宋体', size=14, color='FF000000'),
            'title': Font(name=u'宋体', size=26, color='FF000000'),
            'normal': Font(name='Times New Roman', size=13, color='FF000000'),
            'plan': Font(name='Times New Roman', size=14, color='FF000000')
        }

    def fetch_weather(self):
        """获取天气数据"""
        try:
            url = self.weather_api + self.city
            response = requests.get(url)
            response.raise_for_status()  # 检查请求是否成功
            data = response.json()

            if data.get('status') == 1000:  # 检查API返回状态
                forecast = data['data']['forecast'][0]
                self.weather_data = {
                    'weather': forecast['type'],
                    'temp_high': forecast['high'],
                    'temp_low': forecast['low']
                }
                return True
            else:
                print(f"获取天气失败: {data.get('desc', '未知错误')}")
                return False
        except requests.RequestException as e:
            print(f"网络请求错误: {e}")
            return False
        except (KeyError, json.JSONDecodeError) as e:
            print(f"解析天气数据失败: {e}")
            return False

    def create_daily_plan(self, time_slots=None):
        """创建每日计划"""
        if time_slots is None:
            time_slots = self.default_time_slots

        # 获取天气数据
        if not self.fetch_weather():
            self.weather_data = {'weather': '未知', 'temp_high': '未知', 'temp_low': '未知'}

        try:
            # 加载工作簿
            workbook = load_workbook(self.excel_path)
            sheet = workbook.active

            # 设置基本信息
            sheet["A1"] = "日期"
            sheet["B1"] = time.strftime("%Y/%m/%d")
            sheet["A2"] = "天气"
            sheet["B2"] = self.weather_data['weather']
            sheet["A3"] = "温度"
            sheet["B3"] = self.weather_data['temp_high']
            sheet["C3"] = self.weather_data['temp_low']

            # 设置表头
            sheet["A4"] = "时间安排"
            sheet["B4"] = "计划详情"
            sheet["C4"] = "完成情况"
            sheet["A12"] = "对今天的评价"
            sheet["B12"] = ""

            # 设置样式
            sheet["B1"].fill = self.styles['date']
            sheet["B1"].font = self.fonts['date']
            sheet["B2"].fill = self.styles['weather']
            sheet["B2"].font = self.fonts['date']
            sheet["B3"].fill = self.styles['temp_high']
            sheet["B3"].font = self.fonts['date']
            sheet["C3"].fill = self.styles['temp_low']
            sheet["C3"].font = self.fonts['date']

            # 设置标题样式
            for cell in ['A1', 'A2', 'A3', 'A4', 'B4', 'C4', 'A12']:
                sheet[cell].fill = self.styles['title']
                sheet[cell].font = self.fonts['header']

            sheet["B12"].fill = self.styles['judge']
            sheet["B12"].font = self.fonts['normal']

            # 设置时间和计划
            plans = []
            for i, ti in enumerate(time_slots):
                row = i + 5
                msg = simpledialog.askstring("输入计划", f"{i + 1}. {ti}: ")
                plans.append(msg)

                # 填充时间和计划
                sheet.cell(row, 1).value = ti
                sheet.cell(row, 1).fill = self.styles['time']
                sheet.cell(row, 1).font = self.fonts['plan']

                sheet.cell(row, 2).value = msg
                sheet.cell(row, 2).fill = self.styles['plan']
                sheet.cell(row, 2).font = self.fonts['normal']

                # 初始化完成情况列
                sheet.cell(row, 3).value = ''
                sheet.cell(row, 3).fill = self.styles['plan']

            # 合并单元格
            sheet.merge_cells('B1:C1')
            sheet.merge_cells('B2:C2')
            sheet.merge_cells('B12:C12')

            # 设置工作表标题
            title = time.strftime("%m-%d-%A")
            sheet.title = title

            # 保存工作簿
            workbook.save(self.excel_path)
            workbook.close()

            messagebox.showinfo("计划创建成功", f"今天的天气是: {self.weather_data['weather']}\n今天的温度是: {self.weather_data['temp_high']}-{self.weather_data['temp_low']}\nHave a nice day~~")
            return True
        except PermissionError:
            messagebox.showerror("错误", "Excel软件已经打开，请关闭软件后再运行程序!")
            return False
        except Exception as e:
            messagebox.showerror("错误", f"创建计划时出错: {e}")
            return False

    def review_daily_plan(self):
        """回顾每日计划完成情况"""
        try:
            # 加载工作簿
            workbook = load_workbook(self.excel_path)
            current_sheet = workbook.active

            # 获取当前计划
            times = []
            plans = []
            for i in range(7):
                row = i + 5
                clock = str(current_sheet.cell(row, 1).value)
                plan = str(current_sheet.cell(row, 2).value)
                times.append(clock)
                plans.append(plan)

            # 收集完成情况
            completed_count = 0
            situations = []

            for i in range(7):
                row = i + 5
                answer = simpledialog.askstring("完成情况", f"{i + 1}. {times[i]}: {plans[i]}\n完成情况 (1=完成, 2=未完成, 其他=部分完成并输入原因): ")

                if answer == "1":
                    current_sheet.cell(row, 3).value = "完成"
                    current_sheet.cell(row, 3).fill = self.styles['completed']
                    current_sheet.cell(row, 3).font = self.fonts['normal']
                    completed_count += 1
                    situations.append("完成")
                elif answer == "2":
                    current_sheet.cell(row, 3).value = "未完成"
                    current_sheet.cell(row, 3).fill = self.styles['not_completed']
                    current_sheet.cell(row, 3).font = self.fonts['normal']
                    situations.append("未完成")
                else:
                    explain = simpledialog.askstring("未完成原因", "此项计划没有完成的原因: ")
                    current_sheet.cell(row, 3).value = explain
                    current_sheet.cell(row, 3).fill = self.styles['partial']
                    current_sheet.cell(row, 3).font = self.fonts['normal']
                    situations.append(explain)
                    completed_count += 1

            # 根据完成情况给出评价
            if completed_count < 4:
                score = "真是个臭弟弟，计划完成的不达标!!!"
                fill = self.styles['not_completed']
            elif completed_count >= 6:
                score = "真是太棒了，完美的完成了任务~"
                fill = self.styles['completed']
            else:
                score = "反应平平，计划完成的一般。"
                fill = self.styles['partial']

            # 找到汇总表，如果没有则创建
            summary_sheet_title = "每日计划情况汇总"
            if summary_sheet_title not in workbook.sheetnames:
                summary_sheet = workbook.create_sheet(summary_sheet_title)
            else:
                summary_sheet = workbook[summary_sheet_title]

            # 在汇总表中记录
            current_date = time.strftime("%m-%d")
            found = False

            for r in range(1, summary_sheet.max_row + 1):
                for c in range(1, summary_sheet.max_column + 1):
                    if str(summary_sheet.cell(r, c).value) == current_date:
                        found = True

                        # 记录评分
                        summary_sheet.cell(r, c + 4).value = "☆" if completed_count < 4 else "★" if completed_count >= 6 else "●＿●"
                        summary_sheet.cell(r, c + 4).fill = fill
                        summary_sheet.cell(r, c + 4).font = self.fonts['title'] if completed_count < 4 or completed_count >= 6 else self.fonts['plan']

                        # 随机选择一种颜色
                        color_index = choice(range(len(self.styles['review'])))

                        # 记录详细计划
                        for i in range(7):
                            summary_sheet.cell(r + i, c + 1).value = times[i]
                            summary_sheet.cell(r + i, c + 1).fill = self.styles['review'][color_index]

                            summary_sheet.cell(r + i, c + 2).value = plans[i]
                            summary_sheet.cell(r + i, c + 2).fill = self.styles['review'][color_index]

                            summary_sheet.cell(r + i, c + 3).value = situations[i]
                            if situations[i] == "未完成":
                                summary_sheet.cell(r + i, c + 3).fill = self.styles['not_completed']
                            elif situations[i] == "完成":
                                summary_sheet.cell(r + i, c + 3).fill = self.styles['completed']
                            else:
                                summary_sheet.cell(r + i, c + 3).fill = self.styles['partial']

                        break
                if found:
                    break

            # 获取今日突破
            judge = simpledialog.askstring("今日突破", "你今天做出了哪些突破: ")
            current_sheet["B12"] = f"{score} 今天的突破:【{judge}】"
            current_sheet["B12"].fill = fill

            # 复制当前工作表到新工作表
            copy_sheet = workbook.copy_worksheet(current_sheet)
            copy_sheet.title = time.strftime("%m-%d")

            # 保存工作簿
            workbook.save(self.excel_path)

            messagebox.showinfo("回顾完成", f"今天你完成了{completed_count}项任务，今天的评价是:{score}")
            return True
        except PermissionError:
            messagebox.showerror("错误", "Excel软件已经打开，请关闭软件后再运行程序!")
            return False
        except Exception as e:
            messagebox.showerror("错误", f"回顾计划时出错: {e}")
            return False


def main():
    def select_excel_file():
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel文件", "*.xlsx"), ("所有文件", "*.*")]
        )
        if file_path:
            excel_path.set(file_path)

    def create_plan():
        planner = DailyPlanner(excel_path.get())
        planner.create_daily_plan()

    def review_plan():
        planner = DailyPlanner(excel_path.get())
        planner.review_daily_plan()

    root = tk.Tk()
    root.title("每日计划管理系统")
    root.geometry("400x300")  # 设置窗口大小
    root.configure(bg="#f0f0f0")  # 设置背景颜色

    # 添加图标
    root.iconbitmap(r"C:\Users\11200\Desktop\图标.jpg")  # 替换为你的图标文件路径

    # 创建一个LabelFrame来组织按钮
    frame = ttk.LabelFrame(root, text="操作选项", padding="10 10 10 10")
    frame.pack(pady=20, padx=20, fill="both", expand=True)

    # 添加按钮
    create_button = ttk.Button(frame, text="创建新的每日计划", command=create_plan)
    create_button.pack(pady=10, fill="x")

    review_button = ttk.Button(frame, text="回顾今日计划完成情况", command=review_plan)
    review_button.pack(pady=10, fill="x")

    # 添加Excel文件路径选择
    excel_path = tk.StringVar()
    ttk.Label(frame, text="Excel文件路径:").pack(pady=5)
    ttk.Entry(frame, textvariable=excel_path, width=40).pack(pady=5)
    ttk.Button(frame, text="浏览...", command=select_excel_file).pack(pady=5)

    # 添加退出按钮
    exit_button = ttk.Button(frame, text="退出", command=root.quit)
    exit_button.pack(pady=10, fill="x")

    root.mainloop()


if __name__ == "__main__":
    main()